define(['./../initial', './mapInstance', './../model/PublicMap', './../model/project'], function() {
    var app = angular.module('App.home');
    app.factory('loadMap', ['$q', 'mapInstance', '$rootScope', 'PublicMap', 'Project',
        function($q, mapInstance, $rootScope, PublicMap, Project) {
            return function(para) {
                var deferred = $q.defer();
                var prjs = para.prjs;
                var viewState = {
                    'map': para.mapId,
                    'project': 'project'
                };
                var map = mapInstance.getMap();
                if (map) {
                    map.remove();
                }
                var offsets = {
                    '高德地图': [0, 0],
                    '天地图': [0.00205972005050015, -0.00445783138300726],
                    '天地图影像': [0.00205972005050015, -0.00445783138300726]
                };
                var source = window.localStorage.getItem('preferMap') || '天地图';
                offset = offsets[source];
                var center = [prjs[0].center.lat + offset[0], prjs[0].center.lng + offset[1]];
                map = new PublicMap(para.mapId, {
                    center: center, //上海坐标,默认为地图中心
                    zoom: 17,
                    maxZoom: 18,
                    minZoom: 8,
                    zoomControl: false,
                    doubleClickZoom: false
                });

                map.loadPublicMap(); //加载公共地图,天地图或者高德地图(默认)
                mapInstance.setMap(map, 'map');
                map.addPrjs(prjs); //加载所有项目

                map.on('popupclose', function() {
                    prjStatusChartModalHelper.close();
                });
                map.addEventListener('prjMarkerClick', function(data) {
                    var prj = prjs.filter(function(item) {
                        return item.prjId === data.prjId;
                    })[0];

                    if ($rootScope.curPrj) {
                        $rootScope.curPrj.active = false;
                    }
                    $rootScope.curPrj = prj;
                    $rootScope.curPrj.active = true;


                });

                map.on('baselayerchange', function(eventData) {
                    map.mapSource = eventData.name;
                    window.localStorage.setItem('preferMap', eventData.name);
                    // map.addPrjs(Project.prjs);//重新加载marker图层,有点影响效率,先放一边
                });

                map.on('click', function(data) {
                    // console.log(JSON.stringify(data.latlng));
                });

                deferred.resolve(null);
                return deferred.promise;
            };
        }
    ]);
});
